<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入商品"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['cart:cart:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cart:cart:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cart:cart:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['cart:cart:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cartList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="购物车编号" align="center" prop="cartId" /> -->
      <el-table-column label="用户" align="center" prop="userName" />
      <el-table-column label="商品" align="center" prop="productName" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="总价" align="center" prop="totalAmount" />
      <el-table-column label="添加时间" align="center" prop="addedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.addedDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cart:cart:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cart:cart:remove']">删除</el-button>
        </template>
      </el-table-column>
      
      <!-- 新增地址列 -->
      <el-table-column label="收货地址" align="center" prop="shippingAddress" width="180">
        <template #default="scope">
          <el-button 
            v-if="!scope.row.hasAddress"
            type="text"
            size="small"
            @click="handleAddress(scope.row)"
          >
            添加地址
          </el-button>
          <span v-else>{{ scope.row.shippingAddress }}</span>
        </template>
      </el-table-column>

      <!-- 支付列 -->
      <el-table-column label="支付" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            v-if="scope.row.hasAddress"
            link 
            type="primary" 
            icon="Edit" 
            @click="handlePay(scope.row)" 
            v-hasPermi="['cart:cart:edit']"
          >
            支付
          </el-button>
          <span v-else style="color:#999">请先添加地址</span>
        </template>
      </el-table-column>
    </el-table>

    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
<!-- 地址对话框 -->
<el-dialog title="添加收货地址" v-model="addressOpen" width="500px" append-to-body>
      <el-form :model="addressForm" label-width="80px">
      
        <el-form-item label="联系人姓名">
          <el-input v-model="addressForm. contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人电话">
          <el-input v-model="addressForm. contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="省份">
          <el-input v-model="addressForm.province" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="addressForm.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="区县">
          <el-input v-model="addressForm.district" placeholder="请输入区县" />
        </el-form-item>
        <el-form-item label="详细街道地址">
          <el-input v-model="addressForm.detailAddress" placeholder="请输入详细街道地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addressOpen = false">取消</el-button>
        <el-button type="primary" @click="submitAddress">确定</el-button>
      </template>
    </el-dialog>

    <!-- v-model绑定的变量来控制显示和隐藏的 -->
    <!-- 添加或修改购物车对话框  <el-dialog就是用来定义对话框的-->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="cartRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>




     <!-- 支付对话框 -->
<el-dialog :title="buyTitle" v-model="buy" width="500px" append-to-body>
  <el-form ref="cartRef" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="微信支付">
      <el-button type="success" @click="handleWeChatPay">微信支付</el-button>
    </el-form-item>
    <el-form-item label="支付宝支付">
      <el-button type="primary" @click="handleAlipay">支付宝支付</el-button>
    </el-form-item>
    <el-form-item label="银行卡支付">
      <el-button type="warning" @click="handleBankPay">银行卡支付</el-button>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="buy = false">取 消</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script setup name="Cart">
import { listCart,listCartid, getCart, delCart, addCart, updateCart } from "@/api/cart/cart";
import {addOrders } from "@/api/orders/orders";

import {addPayments } from "@/api/payments/payments";
import {addLogisticsaddress } from "@/api/logisticsaddress/logisticsaddress";
import {sendMessage } from "@/api/webhook/webhook";
import Cookies from 'js-cookie';  //cookies的使用要求引入
import { addLogisticsmaster} from "@/api/logisticsmaster/logisticsmaster";
import { addOrderdetails} from "@/api/orderdetails/orderdetails";
const { proxy } = getCurrentInstance();

const cartList = ref([]);
const cartListid = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const addressOpen = ref(false);
const currentAddressRow = ref(null);

const data = reactive({
  orderId:null,
  form: {},
  fullAddress:"",
  addressForm:{},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: null,
    quantity: null,
    userName: null
  },
  rules: {
    quantity: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
  },
  buy: false, // 控制支付对话框的显示和隐藏
  buyTitle: "选择支付方式" // 支付对话框的标题
});

const { queryParams, form, rules, buy, buyTitle,addressForm ,orderId,fullAddress} = toRefs(data);

// 处理地址
function handleAddress(row) {
  currentAddressRow.value = row;
  addressOpen.value = true;
}
function generateRandomOrderId() {
  // 直接生成 1 ~ 2147483647 的随机整数
  return Math.floor(Math.random() * 2147483647) + 1;
}


/** 查询购物车列表 */
function getList() {

  loading.value = true;
  const userName=Cookies.get("username");
  queryParams.value.userName=userName;
  listCart(queryParams.value).then(response => {
    cartList.value = response.rows.map(item => ({
      ...item,
      // 初始化地址状态
      hasAddress: !!item.shippingAddress,
      shippingAddress: item.shippingAddress || "未设置"
    }));
  });
  loading.value = false;

}

// 提交地址
function submitAddress() {
  orderId.value=generateRandomOrderId();
  addressForm.value.logisticsId=orderId.value;
  addressForm.value.addressType="SENDER";
 
  addLogisticsaddress(addressForm.value).then(response => {
  });
  currentAddressRow.value.hasAddress = true; // 设置地址标志
  addressOpen.value = false;
  proxy.$modal.msgSuccess("地址已保存");
 // 拼接完整的地址字符串
fullAddress.value = `${addressForm.value.province}${addressForm.value.city}${addressForm.value.district}${addressForm.value.detailAddress}`;

// 更新当前行的地址显示
currentAddressRow.value.shippingAddress = fullAddress.value;
}
function handlePay(row) {
  loading.value = true;
  listCartid(queryParams.value).then(response => {
    console.log( response.rows)
    cartListid.value = response.rows;
  });

  loading.value = false;

  // row   js提供的一i给对象，没有value属性，直接用
  form.value=row;


  buy.value = true;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    cartId: null,
    userId: null,
    productId: null,
    quantity: null,
    addedDate: null
  };
  proxy.resetForm("cartRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.cartId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加购物车";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _cartId = row.cartId || ids.value
  getCart(_cartId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改购物车";
  });
}



/** 提交按钮 */
function submitForm() {
  proxy.$refs["cartRef"].validate(valid => {
    if (valid) {
      if (form.value.cartId != null) {
        updateCart(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
        
        });
      } else {
        addCart(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
       
        });
      }
    }
  });
  getList();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _cartIds = row.cartId || ids.value;
  proxy.$modal.confirm('是否确认删除购物车编号为"' + _cartIds + '"的数据项？').then(function() {
    return delCart(_cartIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
  getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('cart/cart/export', {
    ...queryParams.value
  }, `cart_${new Date().getTime()}.xlsx`)
}





function handleWeChatPay() {
  sendOrderRequest("微信支付");
  // 模拟支付成功
  proxy.$modal.msgSuccess("微信支付成功");
  // 准备订单数据并发送请求

}

function handleAlipay() {
  sendOrderRequest("支付宝支付");
  // 模拟支付成功
  proxy.$modal.msgSuccess("支付宝支付成功");
  // 准备订单数据并发送请求

}

function handleBankPay() {
  sendOrderRequest("银行卡支付");
  // 模拟支付成功
  proxy.$modal.msgSuccess("银行卡支付成功");
  // 准备订单数据并发送请求

}
// 支付成功的操作脚本
function sendOrderRequest(paymentMethod) {
  // 准备订单数据
  const orderData = {
    orderId:  orderId.value,
    userName: cartListid.value[0]?.userName, // 访问数组第一项的 userId
    productId: cartListid.value[0]?.productId, // 访问数组第一项的 productId
    quantity: cartListid.value[0]?.quantity, // 访问数组第一项的 quantity
    totalAmount: form.value.totalAmount,
    amount: form.value.totalAmount,
    status: "运输中",
    shippingAddress: "xxxxx",
    paymentMethod: paymentMethod // 使用传入的支付方式
  };


  const payData = {
    userName: cartListid.value[0]?.userName, // 访问数组第一项的 userId
    productId: cartListid.value[0]?.productId, // 访问数组第一项的 productId
    quantity: cartListid.value[0]?.quantity, // 访问数组第一项的 quantity
    totalAmount: form.value.totalAmount,
    amount: form.value.totalAmount,
    orderId: orderId.value,
    status: "支付成功",
    shippingAddress: "xxxxx",
    paymentMethod: paymentMethod // 使用传入的支付方式
  };

console.log(payData);
  const orderDeatails = {
    orderId:payData.orderId,
    productId:payData.productId,
    quantity:payData.quantity,
    price:0
  };
  addOrderdetails(orderDeatails).then(response => {
  });

// 添加物流订单
const userName=Cookies.get("username");
addressForm.value.currentLocation=fullAddress.value;
addressForm.value.addressType="SENDER";
  addressForm.value.userName=userName;
  addressForm.value.distance=0;
  addressForm.value.orderWeight=100;
  addressForm.value.logisticsId =   orderId.value;
  addressForm.value.relatedOrderId= orderId.value;
  addressForm.value.status ="CREATED";
  addLogisticsmaster(addressForm.value).then(response => {
    addLogisticsaddress(addressForm.value).then(response => {
    
  });
  });
 



  // 添加订单
  // 调用 addOrders 方法发送请求
  console.log(orderData);
  addOrders(orderData).then(response => {
    proxy.$message.success("订单已成功创建");
    buy.value = false;
    getList();
  }).catch(error => {
    proxy.$message.error("订单创建失败");
  });
  getList();

  addPayments(payData).then(response => {
    proxy.$message.success("成功记录支付信息");
    const message='您的物流订单已生成';
    sendMessage(message);
 
    buy.value = false;
    getList();
    setTimeout(() => {
    const message01 = '您的货品开始运输了';
    sendMessage(message01);
  
  }, 1000);
  }
  
).catch(error => {
    proxy.$message.error("失败记录支付信息");
  });
}

getList();
</script>
